package com.shreecon.lms.persistancy;

import org.hibernate.Session;
import org.hibernate.Transaction;
import static com.shreecon.lms.interfaces.IMessageConstant.TECH_ERROR;
import com.shreecon.lms.interfaces.LMSException;
import com.shreecon.lms.interfaces.persistance.IShreeConsDAO;

/**
 * The Class ShreeConsDAO.
 * 
 * @author Santhosh. Modified on Aug 13, 2011
 */
public class ShreeConsDAO implements IShreeConsDAO{

	/* (non-Javadoc)
	 * @see com.shreecon.lms.persistancy.IShreeConsDAO#save(java.lang.Object)
	 */
	public void save(Object transientInstance) throws LMSException{
		Session session = HibernateAccessUtil.getInstance().getSession();
		try {
			Transaction transaction = session.beginTransaction();
			session.save(transientInstance);
			transaction.commit();
			System.out.println("saved");
		} catch (RuntimeException re) {
			throw new LMSException(TECH_ERROR,re);
		}
		finally{
			HibernateAccessUtil.getInstance().closeSession(session);
		}
	}
	
	/* (non-Javadoc)
	 * @see com.shreecon.lms.persistancy.IShreeConsDAO#saveOrUpdate(java.lang.Object)
	 */
	public void saveOrUpdate(Object transientInstance)  throws LMSException{
		Session session = HibernateAccessUtil.getInstance().getSession();
		try {
			Transaction transaction = session.beginTransaction();
			session.saveOrUpdate(transientInstance);
			transaction.commit();
			System.out.println("saved");
		} catch (RuntimeException re) {
			throw new LMSException(TECH_ERROR,re);
		}
		finally{
			HibernateAccessUtil.getInstance().closeSession(session);
		}
	}


	/* (non-Javadoc)
	 * @see com.shreecon.lms.persistancy.IShreeConsDAO#delete(java.lang.Object)
	 */
	public void delete(Object persistentInstance) throws LMSException {
		Session session = HibernateAccessUtil.getInstance().getSession();
		try {
			Transaction transaction = session.beginTransaction();
			session.delete(persistentInstance);
			transaction.commit();
			System.out.println("deleted");
		} catch (RuntimeException re) {
			throw new LMSException(TECH_ERROR,re);
		}
		finally{
			HibernateAccessUtil.getInstance().closeSession(session);
		}
		
	}

	/* (non-Javadoc)
	 * @see com.shreecon.lms.persistancy.IShreeConsDAO#findById(java.lang.Long, java.lang.Class)
	 */
	@SuppressWarnings("unchecked")
	public Object findById(Long id,Class hbmInstance) throws LMSException {
		Session session = HibernateAccessUtil.getInstance().getSession();
		try {
			Object instance = (Object) session.get( hbmInstance, id);
			if (instance == null) {
				System.err.println("Not found");
			} else {
				System.out.println("record found");
			}
			return instance;
			
		} catch (RuntimeException re) {
			throw new LMSException(TECH_ERROR,re);
		} finally{
			HibernateAccessUtil.getInstance().closeSession(session);
		}
	}
}
